package com.basker.pisces.concurrent.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class LocalLock extends AbstractLock {

    /**
     * 公平锁，先到先得
     */
    private ReentrantLock lock = new ReentrantLock(true);

    public LocalLock(String key) {
        super(key);
    }

    @Override
    public boolean lock() {
        return lock.tryLock();
    }

    /**
     * 本地锁不支持leaseTime功能，该方法等价于{@link #lock(long, TimeUnit)}
     */
    @Override
    public boolean lock(long waitTime, long leaseTime, TimeUnit unit) {
        return lock(waitTime, unit);
    }

    @Override
    public boolean lock(long waitTime, TimeUnit unit) {
        try {
            return lock.tryLock(waitTime, unit);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    @Override
    public boolean unlock() {
        if (!this.lock.isHeldByCurrentThread()) {
            return false;
        }

        try {
            this.lock.unlock();
            return true;
        } catch (IllegalMonitorStateException e) {
            return false;
        }
    }

}
